import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class MasterListener extends Thread {

	DatagramSocket ds = null;
	public final static int PORT = 8765;
	IMaster messageHandler = null;
	boolean keepRunning = true;
	
	public MasterListener(IMaster master) {
		try {
			ds = new DatagramSocket(PORTS.MASTER_LISTENER_PORT_FOR_SLAVE);
			messageHandler = master;
		} 
		catch (SocketException e) {
			e.printStackTrace();
			keepRunning = false;
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("before running ");
		while(keepRunning){
			byte[] buf = new byte[256];        
	        DatagramPacket packet = new DatagramPacket(buf, buf.length);
	        try {
				ds.receive(packet);
				System.out.println("after receive packet ");
			} 
	        catch (IOException e) {
	        	keepRunning = false;
				e.printStackTrace();
			}
	        IMessage message = new Message();
	        message.deserialize(buf);
	        //message.setMessageID(IMessage.MESSAGE_FROM_SLAVE);
	        messageHandler.handleMessage(message);
		}
	}
}
